# coding=utf-8
import hashlib
from django.conf import settings
from rest_framework.response import Response
from functools import wraps


def sig(data_dict, appkey):
    '''
    data_dict = {'apiversion': '',
                 'flyer': '1435730811643', 'sid': '', 'u': '1',
                 'log_user_id': '18511871276@sohu.com',
                 'p1': '', 'appid': '860000', 'column_id': '0', 'pid': '',
                 'user_id': '18511871276@sohu.com',
                 'profile_user_id': '1737847545@sina.sohu.com'}
    '''
    sig_string = ""
    for key in sorted(data_dict.keys()):
        if key != 'sig':
            sig_string += key + "=" + str(data_dict[key])
    sig_str = sig_string + appkey
    sig_str = sig_str.encode('utf-8')
    sig_md5 = hashlib.md5()
    sig_md5.update(sig_str)
    return sig_md5.hexdigest()


def auth_check(func):
    @wraps(func)
    def _warp(self, request, *args, **kwargs):
        if request.method != 'GET':
            request_sig = request.data.get('sig', None)
            data = {}
            for key in request.data:
                if key != 'sig':
                    data[key] = request.data[key]
        else:
            request_sig = request.query_params.get('sig', None)
            data = {}
            for key in request.query_params:
                if key != 'sig':
                    data[key] = request.query_params[key]

        if 'appid' not in data or 'flyer' not in data:
            context = {
                'status': 401,
                'msg': 'forbidden'
            }
            return Response(context)
        self.appid = str(data['appid'])
        appkey = settings.AUTH_APPKEYS[self.appid]
        server_sig = sig(data, appkey)
        if server_sig != request_sig:
            context = {
                'status': 401,
                'msg': 'forbidden'
            }
            return Response(context)
        return func(self, request, *args, **kwargs)
    return _warp
